<?php
namespace app\console\controller;

use extra\Constant;
use think\Db;
use think\cache\driver\Redis;
use think\Config;

use app\console\model\MessageBox;
use app\console\model\SendJpush;
use app\console\model\Customer as CustomerModel;
use app\console\model\MessageTargetUser as MessageTargetUserModel;

class MessageUser{
    /*
     * 分组写入数据
     * 执行频率:每分钟一次
     */
    public function writeData(){
        /*
         * 从消息表读取今天要发送的消息
         */
        $messageBox=new MessageBox;
        $messageNotice=$messageBox->getPushedMessage();
        if(!empty($messageNotice)){
            
            //1:所有用户,2:未下单用户,3:还款中用户,4:已逾期用户,5:指定用户
           
            
            foreach ($messageNotice as $v){
                if($v['target_user']==1){//全部用户
                    $this->pushToAllCustomer($v['id'],$v['add_time']);
                }
                
                if($v['target_user']==2){//未下单用户
//                    $this->pushToNoOrderCustomer($v['id'],$v['add_time']);
                }
                if($v['target_user']==5){
                    $this->pushToTargetCustomer($v['id'],$v['add_time']);
                }
                
                //$this->pushToAllCustomer($v['id'],$v['add_time']);
                    
                //更改消息状态
                $status=$messageBox->updateIsreleaseSendByID($v['id']);
                if($status){
                    break;
                }
                
            }
    
            //$this->pushToAllCustomer(1);
            
        }
        
    }
    
    /*
     * 推送给指定用户
     */
    public function pushToTargetCustomer($msgID,$addTime){
        $messageTargetUserModel=new MessageTargetUserModel;
        $data=$messageTargetUserModel->getDataByMsgId($msgID,$addTime,$field='id,customer_id');
        if(!empty($data)){
            foreach ($data as $v){
                //用户ID,ID
                
                //用户是否处于活跃状态
                if(!$this->customerIsActive($v['customer_id'])){//用户不处于活跃状态
                    continue;
                }
                //用户设备ID
                $customerModel=new CustomerModel;
                $customerData=$customerModel->getPushIdByCustomerID($v['customer_id']);
                if(!$customerData['push_id']){
                    continue;
                }
                //用户设备类型 IOS或者安卓
                $customerModel=new CustomerModel;
                $consumeData=$customerModel->getCustomerLastConsumeData($v['customer_id']);
    
                $pushModel=new SendJpush;
                $pushData=['pushId'=>$customerData['push_id'],'systemType'=>$consumeData['system_type']];
                $re=$pushModel->pushUnreadMessages($pushData);
                $pushRe=json_decode($re,true);
                $status=1;
                if(isset($pushRe['sendno']) && $pushRe['sendno']=='0'){
                    $status=2;
                }
    
                /*
                 * 更新目标用户表
                 */
                $messageTargetUserModel=new MessageTargetUserModel;
                $messageTargetUserModel->updatajpushSendStatusByID($v['id'],$status,$addTime);
                
                
            }
        }
    }
    
    /*
     * 发送消息给未下单用户
     */
    public  function pushToNoOrderCustomer($msgId,$addTime){
        
        $sql='SELECT
	count(customer.id) 

FROM
	customer
WHERE
	customer.push_id != \'\'
AND id NOT IN(
	SELECT
		customer_id
	FROM
		consume_history
	WHERE
		(
			`status` = 3
			OR `status` = 8
			OR `status` = 12
			OR `status` = 7
		)
	GROUP BY
		customer_id
)';
    
                
        $tianshendai_read=Db::connect("tianshendai_read");
        //分1000条为一组，分多组去处理
        $pageLimit=1000;//单页数据取出量
        $totalNum=$tianshendai_read->name("customer")->query($sql);
        $pageNum=ceil($totalNum/$pageLimit);//总页数
        for($i=1;$i<=$pageNum;$i++){
            $dataObj1=$tianshendai_read->name("customer")->field('id,push_id')->where(['push_id'=>['neq','']])->order(['id'=>'desc'])->paginate(['list_rows'=>$pageLimit,'page'=>$i]);
            $customerData=$dataObj1->all();
            if(!empty($customerData)){
                $redis=new Redis(Config::get('redis'));
                foreach ($customerData as $v){
                    /*
                     * 是否是活跃用户
                     */
                    $cacheKey = 'To'.$v['id'].'ken';
                    if(!$redis->get($cacheKey)){//用户不处于活跃状态
                        continue;
                    }
                
                    /*
                     * 取出最后一条订单数据 获取设备类型
                     */
                    $customerModel=new CustomerModel;
                    $consumeData=$customerModel->getCustomerLastConsumeData($v['id']);
                
                    $pushModel=new SendJpush;
                    $pushData=['pushId'=>$v['push_id'],'systemType'=>$consumeData['system_type']];
                    $re=$pushModel->pushUnreadMessages($pushData);
                    $pushRe=json_decode($re,true);
                    $status=1;
                    if(isset($pushRe['sendno']) && $pushRe['sendno']=='0'){
                        $status=2;
                    }
                    
                    /*
                     * 写入目标用户表
                     */
                    $addData=['m_b_id'=>$msgId,'customer_id'=>$v['id'],'type'=>2,'jpush_send_status'=>$status,'add_time'=>time()];
                    $messageTargetUserModel=new MessageTargetUserModel;
                    $messageTargetUserModel->addMessageTargetUserData($addData,$addTime);
                }
                unset($dataObj1,$customerData);
                sleep(1);
            
            }
        }
    }
    
    
    /*
     * 发送消息给全部用户
     */
    public function pushToAllCustomer($msgId,$addTime){
        $tianshendai_read=Db::connect("tianshendai_read");
        //分1000条为一组，分多组去处理
        $pageLimit=1000;//单页数据取出量
        $totalNum=$tianshendai_read->name("customer")->where(['push_id'=>['neq','']])->count('id');
        $pageNum=ceil($totalNum/$pageLimit);//总页数
        for($i=1;$i<=$pageNum;$i++){
            $dataObj1=$tianshendai_read->name("customer")->field('id,push_id')->where(['push_id'=>['neq','']])->order(['id'=>'desc'])->paginate(['list_rows'=>$pageLimit,'page'=>$i]);
            $customerData=$dataObj1->all();
            if(!empty($customerData)){
                foreach ($customerData as $v){
                    /*
                     * 是否是活跃用户
                     */
                    if(!$this->customerIsActive($v['id'])){//用户不处于活跃状态
                        continue;
                    }
                    
                    /*
                     * 取出最后一条订单数据 获取设备类型
                     */
                    $customerModel=new CustomerModel;
                    $consumeData=$customerModel->getCustomerLastConsumeData($v['id']);
                    
                    $pushModel=new SendJpush;
                    $pushData=['pushId'=>$v['push_id'],'systemType'=>$consumeData['system_type']];
                    $re=$pushModel->pushUnreadMessages($pushData);
                    $pushRe=json_decode($re,true);
                    $status=1;
                    if(isset($pushRe['sendno']) && $pushRe['sendno']=='0'){
                        $status=2;
                    }
                    
                    /*
                     * 写入目标用户表
                     */
                    $addData=['m_b_id'=>$msgId,'customer_id'=>$v['id'],'type'=>2,'jpush_send_status'=>$status,'add_time'=>time()];
                    $messageTargetUserModel=new MessageTargetUserModel;
                    $messageTargetUserModel->addMessageTargetUserData($addData,$addTime);
                }
                unset($dataObj1,$customerData);
                sleep(1);
                
            }
        }
    }
    
    
    private function customerIsActive($customerID) {
        if(!(int)$customerID)return false;
        $redis=new Redis(Config::get('redis'));
        $cacheKey = 'To'.$customerID.'ken';
        if(!$redis->get($cacheKey)){//用户不处于活跃状态
            return false;
        }
        return true;
    }
    
    
    
    
}


















